/**
 * @author Roger Wu
 */

(function($) {
    var allSelectBox = [];
    var killAllBox = function(bid) {
        $.each(allSelectBox, function(i) {
            if (allSelectBox[i] != bid) {
                if (!$("#" + allSelectBox[i])[0]) {
                    $("#op_" + allSelectBox[i]).remove();
                    //allSelectBox.splice(i,1);
                } else {
                    $("#op_" + allSelectBox[i]).css({height: "", width: ""}).hide();
                }
                $(document).unbind("click", killAllBox);
            }
        });
    };

    $.extend($.fn, {
        comboxSelect: function(options) {
            var op = $.extend({selector: ">a"}, options);

            return this.each(function() {
                var box = $(this);
                var selector = $(op.selector, box);

                allSelectBox.push(box.attr("id"));
                $(op.selector, box).click(function() {
                    var options = $("#op_" + box.attr("id"));
                    if (options.is(":hidden")) {
                        if (options.height() > 300) {
                            options.css({height: "300px", overflow: "scroll"});
                        }
                        var top = box.offset().top + box[0].offsetHeight - 50;
                        if (top + options.height() > $(window).height() - 20) {
                            top = $(window).height() - 20 - options.height();
                        }
                        options.css({top: top, left: box.offset().left}).show();
                        killAllBox(box.attr("id"));
                        $(document).click(killAllBox);
                    } else {
                        $(document).unbind("click", killAllBox);
                        killAllBox();
                    }
                    return false;
                });
                $("#op_" + box.attr("id")).find(">li").comboxOption(selector, box);
            });
        },
        comboxOption: function(selector, box) {
            return this.each(function() {
                $(">a", this).click(function() {
                    var $this = $(this);
                    $this.parent().parent().find(".selected").removeClass("selected");
                    $this.addClass("selected");
                    selector.text($this.text());

                    var $input = $("select", box);
                    if ($input.val() != $this.attr("value")) {
                        $("select", box).val($this.attr("value")).trigger("change");
                    }
                });
            });
        },
        combox: function() {
            /* 清理下拉层 */
            var _selectBox = [];
            $.each(allSelectBox, function(i) {
                if ($("#" + allSelectBox[i])[0]) {
                    _selectBox.push(allSelectBox[i]);
                } else {
                    $("#op_" + allSelectBox[i]).remove();
                }
            });
            allSelectBox = _selectBox;

            return this.each(function(i) {
                var $this = $(this).removeClass("combox");
                var name = $this.attr("name");
                var width = $this.attr('width');
                var value = $this.val();
                var label = $("option[value=" + value + "]", $this).text();
                var ref = $this.attr("ref");
                var refUrl = $this.attr("refUrl") || "";
                var refValue = $this.attr("refValue") || "";

                var cid = $this.attr("id") || Math.round(Math.random() * 10000000);
                var select = '<div class="combox"><div id="combox_' + cid + '" class="select"' + (ref ? ' ref="' + ref + '"' : '') + '>';
                select += '<a href="javascript:" class="' + $this.attr("class") + '" name="' + name + '" value="' + value + '" ';
                if (width) {
                    select += 'style="width:' + width + 'px;"';
                }
                select += '>' + label + '</a></div></div>';
                var options = '<ul class="comboxop" id="op_combox_' + cid + '">';
                $("option", $this).each(function() {
                    var option = $(this);
                    options += "<li><a class=\"" + (value == option[0].value ? "selected" : "") + "\" href=\"#\" value=\"" + option[0].value + "\"  ";
                    if (width) {
                        options += 'style="width:' + width + 'px;"';
                    }
                    options += ">" + option[0].text + "</a></li>";
                });
                options += "</ul>";

                $("body").append(options);
                $this.after(select);
                $("div.select", $this.next()).comboxSelect().append($this);

                if (ref && refUrl) {
                    function _onchange(event) {
                        var $ref = $("#" + ref);
                        if ($ref.size() == 0)
                            return false;
                        $.ajax({
                            type: 'POST', dataType: "json", url: decodeURI(refUrl).replace("[value]", encodeURIComponent($this.attr("value"))), cache: false,
                            data: {},
                            global: false,
                            success: function(json) {
                                if (!json)
                                    return;
                                var html = '';
                                $.each(json, function(i) {
                                    if (json[i] && json[i].length > 1) {
                                        html += '<option value="' + json[i][0] + '"';
                                        if (refValue && refValue == json[i][0]) {
                                            html += 'selected="selected"';
                                            $this.attr('refValue', '');
                                            refValue = "";
                                        }
                                        html += '>' + json[i][1] + '</option>';
                                    }
                                });

                                var $refCombox = $ref.parents("div.combox:first");
                                $ref.html(html).insertAfter($refCombox);
                                $refCombox.remove();
                                $ref.trigger("change").combox();
                            },
                            error: DWZ.ajaxError
                        });
                    }

                    $this.unbind("change", _onchange).bind("change", _onchange);
                }

            });
        }
    });
})(jQuery);
